#include "WatchController.h"
I2C_BM8563 rtc(I2C_BM8563_DEFAULT_ADDRESS, Wire);

WatchController::WatchController()
{
}

WatchController::~WatchController()
{
}

void WatchController::init()
{
    Wire.begin();
    // Init RTC
    rtc.begin();
    rtc.getDate(&dateStruct);
    rtc.getTime(&timeStruct);

    char buffer[50]; // Adjust the buffer size as needed

    // Format the date and time information into the buffer
    snprintf(buffer, sizeof(buffer), "%04d/%02d/%02d %02d:%02d:%02d\n",
             dateStruct.year,
             dateStruct.month,
             dateStruct.date,
             timeStruct.hours,
             timeStruct.minutes,
             timeStruct.seconds);

    // Print the formatted date and time from the buffer
    Serial.print(buffer);
    view.create();
}

void WatchController::onViewLoad()
{
    // model.init();
    // view.create();
    view.load();                   // setup the lvgl display enviroment.
    updateTimer = lv_timer_create( // start the timers.
        [](lv_timer_t *timer)
        {
            WatchController *controller = (WatchController *)timer->user_data;
            controller->update(); // get the time
        },
        1000,
        this);
}

void WatchController::onViewDisappear()
{
    deleteTimer();
    // view.destroy();  // ?why  ,increase the speed ?
    // model.deinit();
}

void WatchController::update()
{
    rtc.getTime(&timeStruct);
    lv_img_set_angle(view.ui.img_hour, (timeStruct.hours * 300 + timeStruct.minutes * 5) % 3600);
    lv_img_set_angle(view.ui.img_minute, timeStruct.minutes * 60 + timeStruct.seconds);
    lv_img_set_angle(view.ui.img_second, timeStruct.seconds * 60);
}

void WatchController::deleteTimer()
{
    if (updateTimer != NULL)
    {
        lv_timer_del(updateTimer);
        updateTimer = NULL;
    }
}